package evaluator

import (
	"fmt"
	"lark/src/ast"
	"lark/src/exception"
	"lark/src/lib/request"
	"lark/src/lib/sqlite"
	"lark/src/loader"
	"lark/src/object"
	"path/filepath"
	"strconv"
	"unicode"
)

type Evaluator struct {
	module       *loader.ModuleLoader
	env          *object.Environment //符号表
	errorHandler *exception.ErrorHandler
}

var evaluator *Evaluator

var (
	NULL  = &object.Null{}
	TRUE  = &object.Boolean{Value: true}
	FALSE = &object.Boolean{Value: false}
)

func NewEvaluator(env *object.Environment, errorHandler *exception.ErrorHandler) {
	evaluator = &Evaluator{
		// 创建模块加载器，搜索路径为当前目录
		module:       loader.NewModuleLoader([]string{"."}),
		env:          env,
		errorHandler: errorHandler,
	}
}

func Eval(node ast.Node, env *object.Environment) object.Object {

	switch node := node.(type) {
	case *ast.Program:
		//函数声明提升
		hoistFunctions(node, env)
		return evalProgram(node, env)
	case *ast.LetStatement:
		val := Eval(node.Value, env)
		//判断是否是内置函数
		/* if builtin, ok := builtins[node.Value]; ok {
			return builtin
		} */
		//放到符号表中
		// env.Set(node.Name.Value, val)

		//判断首字母是否大写，大写是公共的，小写是私有的
		exported := false
		if unicode.IsUpper(rune(node.Name.Value[0])) {
			exported = true
		}

		fmt.Println(" ")
		fmt.Println(" letStatement:", node, "\n")
		fmt.Println(" letStatement:", node.Name.Value, "\n")
		fmt.Println(" letStatement:", val, "\n")

		env.Set(node.Name.Value, object.Symbol{
			Name: node.Name.Value,
			// Value: nil, // 延迟计算
			Value:    val, // 延迟计算
			Node:     node,
			Exported: exported,
		})

	/* case *ast.AssignStatement:
	//等号赋值
	fmt.Println("AssignStatement:", node, "\n")
	//右侧的变量
	rightValue := Eval(node.Value, env)
	fmt.Println(rightValue)

	//判断左侧的变量是否在符号表中
	if _, ok := env.Get(node.Name.Value); ok {
		//放到符号表中
		env.Set(node.Name.Value, rightValue)
	} else {
		return exception.Evaluator(10000, node.Token.Line, "未定义变量\""+node.Name.Value+"\"")
	} */
	case *ast.Identifier:
		// fmt.Println("Identifier:", node, "\n")

		//标识符
		return evalIdentifier(node, env)
	case *ast.Boolean:
		return nativeBoolToBooleanObject(node.Value)
	case *ast.IntegerLiteral:
		//整数
		return &object.Integer{Value: node.Value}
	case *ast.FloatLiteral:
		//浮点数
		return &object.Float{Value: node.Value}
	case *ast.StringLiteral:
		//字符串
		return &object.String{Value: node.Value}
	case *ast.ExpressionStatement:
		return Eval(node.Expression, env)
	case *ast.PrefixExpression:
		//前缀表达式
		right := Eval(node.Right, env)
		return evalPrefixExpression(node.Operator, right)
	case *ast.InfixExpression:
		left := Eval(node.Left, env)
		right := Eval(node.Right, env)
		return evalInfixExpression(node.Operator, left, right)
	case *ast.ReturnStatement:
		val := Eval(node.ReturnValue, env)
		/* if isError(val) {
			return val
		} */
		return &object.ReturnValue{Value: val}
	case *ast.IfExpression:
		return evalIfExpression(node, env)
	case *ast.ForExpression:
		// return evalForExpression(node, env)

		// Eval(node.InitialValue, env)
		/* condition := Eval(node.Condition, env)

		for condition.Inspect() == "true" {

			return evalForExpression(node, env)
		} */
		return evalForExpression(node, env)
	case *ast.BlockStatement:
		return evalBlockStatement(node, env)
	case *ast.FunctionLiteral:

		name := node.Name
		params := node.Parameters
		body := node.Body
		resultFunc := &object.Function{Name: name, Parameters: params, Env: env, Body: body}
		fmt.Println("resultFunc:", resultFunc)

		//判断首字母是否大写，大写是公共的，小写是私有的
		exported := false
		if unicode.IsUpper(rune(name[0])) {
			exported = true
		}
		//放到符号表中
		// env.Set("func_"+name, resultFunc)
		env.Set("func_"+name, object.Symbol{
			Name: "func_" + name,
			// Value: nil, // 延迟计算
			Value:    resultFunc, // 延迟计算
			Node:     node,
			Exported: exported,
		})
		// env.Set(node.Name, resultFunc)

		return resultFunc
	case *ast.CallExpression:
		// fmt.Println("callExpression:", node.Function)
		/* fmt.Println(node.Token)
		fmt.Println(node.Function.TokenLiteral())
		fmt.Printf("%#v\n", node) */
		// fmt.Printf("%#v\n", node)
		function := Eval(node.Function, env)
		/* if isError(function) {
			return function
		} */
		args := evalExpressions(node.Arguments, env)

		/* if len(args) == 1 && isError(args[0]) {
			return args[0]
		} */
		// fmt.Printf("%#v\n", node.Function)
		applyFunc := applyFunction(node.Function.TokenLiteral(), function, args)
		/* if applyFunc == nil {
			applyFunc = Eval(node, env)
			return exception.Evaluator(function.(*object.Error).Line, "未定义的函数: %s", node.Function.TokenLiteral()+"()")
		} */
		return applyFunc
	case *ast.ArrayLiteral:

		elements := evalExpressions(node.Elements, env)
		if len(elements) == 1 && isError(elements[0]) {
			return elements[0]
		}
		return &object.Array{Elements: elements}

	case *ast.IndexExpression:
		left := Eval(node.Left, env)
		if isError(left) {
			return left
		}
		index := Eval(node.Index, env)
		if isError(index) {
			return index
		}
		right := Eval(node.Right, env)
		if isError(right) {
			return right
		}
		return evalIndexExpression(left, index, right)

		/* case *ast.ImportLiteral:

		val := Eval(node.Value, env)
		//放到符号表中
		env.Set(node.node.Name, val)

		return &object.Import{Name: node.Name, Value: node.Value} */
	case *ast.HashLiteral:
		return evalHashLiteral(node, env)
	case *ast.ImportStatement:
		return parseImport(node, env)
	case *ast.ModuleAccess:
		fmt.Println("我在这里")
		return moduleAccess(node, env)
		/* case *ast.ObjectPropertyAccess:
		       return evalPropertyAccess(node, env)
		   case *ast.MethodCall:
		       return evalMethodCall(node, env) */
	case *ast.AccessExpression:

		fmt.Println("我在这里11")
		return evalAccessExpression(node, env)
	}

	return nil
}

func evalProgram(program *ast.Program, env *object.Environment) object.Object {
	var result object.Object

	for _, statement := range program.Statements {
		result = Eval(statement, env)

		switch result := result.(type) {
		case *object.ReturnValue:
			return result.Value
		case *object.Error:
			return result
		}
	}

	return result
}

// 标识符
func evalIdentifier(node *ast.Identifier, env *object.Environment) object.Object {
	//获取符号表中的标识符
	if val, ok := env.Get(node.Value); ok {
		return val.Value
	} else {
		//判断是不是函数
		if val, ok := env.Get("func_" + node.Value); ok {
			return val.Value
		}
	}

	// fmt.Println("evalIdentifier:", node.Value)

	//判断是否是内置函数
	if builtin, ok := builtins[node.Value]; ok {
		return builtin
	}
	//判断是否是模块
	// return evalAccessExpression(node, env)

	/* // 如果在普通环境中找不到，检查是否是模块
	if mod, ok := modules[node.Value]; ok {
		// 动态创建模块对象（如果之前没导入过）
		return createModuleObject(mod)
	} */

	return exception.Evaluator(10000, node.Token.Line, "未定义变量\""+node.Value+"\"")
	// return evaluator.errorHandler.RuntimeError("未定义变量\"" + node.Value + "\"")
}

func nativeBoolToBooleanObject(input bool) *object.Boolean {
	if input {
		return TRUE
	}
	return FALSE
}

// 前缀表达式
func evalPrefixExpression(operator string, right object.Object) object.Object {
	switch operator {
	case "!":
		//逻辑运算符取返
		return evalBangOperatorExpression(right)
	case "-":
		return evalMinusPrefixOperatorExpression(right)
	default:
		// fmt.Println(operator)
		return exception.Evaluator(20000, 0, "未知运算符: %s %s", operator, right.Type())
		// return exception.Error(fmt.Sprintf("未知运算符: %s %s", operator, right.Type()))
	}
}

func evalBangOperatorExpression(right object.Object) object.Object {
	switch right {
	case TRUE:
		return FALSE
	case FALSE:
		return TRUE
	case NULL:
		return TRUE
	default:
		return FALSE
	}
}

func evalMinusPrefixOperatorExpression(right object.Object) object.Object {
	if right.Type() != object.INTEGER_OBJ {
		return exception.Evaluator(20000, 0, "未知运算符: -%s", right.Type())
		// return exception.Error(fmt.Sprintf("未知运算符: -%s", right.Type()), 0)
	}

	value := right.(*object.Integer).Value
	return &object.Integer{Value: -value}
}

func isError(obj object.Object) bool {
	if obj != nil {
		return obj.Type() == object.ERROR_OBJ
	}
	return false
}

func evalInfixExpression(operator string, left, right object.Object) object.Object {
	switch {
	case left.Type() == object.INTEGER_OBJ || right.Type() == object.INTEGER_OBJ || left.Type() == object.FLOAT_OBJ || right.Type() == object.FLOAT_OBJ:
		return evalIntegerInfixExpression(operator, left, right)
	case left.Type() == object.STRING_OBJ && right.Type() == object.STRING_OBJ:
		return evalStringInfixExpression(left, right)
	case operator == "==":
		return nativeBoolToBooleanObject(left == right)
	case operator == "!=":
		return nativeBoolToBooleanObject(left != right)
	default:
		return exception.Evaluator(20000, 0, "未知运算符: %s %s %s", left.Type(), operator, right.Type())
	}
}

func evalIntegerInfixExpression(operator string, left, right object.Object) object.Object {

	switch operator {
	case "+":
		//字符串拼接数字
		if left.Type() == object.STRING_OBJ || right.Type() == object.STRING_OBJ {
			return &object.String{Value: left.Inspect() + right.Inspect()}
		} else {
			amount := countIntAndFloat(operator, left, right)
			if _, ok := amount.(float64); ok {
				return &object.Float{Value: amount.(float64)}
			} else {
				return &object.Integer{Value: amount.(int64)}
			}
		}

	case "-":
		amount := countIntAndFloat(operator, left, right)
		if _, ok := amount.(float64); ok {
			return &object.Float{Value: amount.(float64)}
		} else {
			return &object.Integer{Value: amount.(int64)}
		}
	case "*":
		amount := countIntAndFloat(operator, left, right)
		if _, ok := amount.(float64); ok {
			return &object.Float{Value: amount.(float64)}
		} else {
			return &object.Integer{Value: amount.(int64)}
		}
	case "/":
		amount := countIntAndFloat(operator, left, right)
		if _, ok := amount.(float64); ok {
			return &object.Float{Value: amount.(float64)}
		} else {
			return &object.Integer{Value: amount.(int64)}
		}
	case "<":
		leftVal := left.(*object.Integer).Value
		rightVal := right.(*object.Integer).Value
		return nativeBoolToBooleanObject(leftVal < rightVal)
	case ">":
		leftVal := left.(*object.Integer).Value
		rightVal := right.(*object.Integer).Value
		return nativeBoolToBooleanObject(leftVal > rightVal)
	case "<=":
		leftVal := left.(*object.Integer).Value
		rightVal := right.(*object.Integer).Value
		return nativeBoolToBooleanObject(leftVal <= rightVal)
	case ">=":
		leftVal := left.(*object.Integer).Value
		rightVal := right.(*object.Integer).Value
		return nativeBoolToBooleanObject(leftVal >= rightVal)
	case "==":
		leftVal := left.(*object.Integer).Value
		rightVal := right.(*object.Integer).Value
		return nativeBoolToBooleanObject(leftVal == rightVal)
	case "!=":
		leftVal := left.(*object.Integer).Value
		rightVal := right.(*object.Integer).Value
		return nativeBoolToBooleanObject(leftVal != rightVal)
	default:
		return exception.Evaluator(20000, 0, "未知运算符: %s %s %s", left.Type(), operator, right.Type())
	}
}

// 计算数字并且判断是不是浮点型
func countIntAndFloat(operator string, left, right object.Object) interface{} {

	if left.Type() == "FLOAT" {
		if right.Type() != "FLOAT" {
			if operator == "+" {
				return left.(*object.Float).Value + float64(right.(*object.Integer).Value)
			} else if operator == "-" {
				return left.(*object.Float).Value - float64(right.(*object.Integer).Value)
			} else if operator == "*" {
				return left.(*object.Float).Value * float64(right.(*object.Integer).Value)
			} else if operator == "/" {
				return left.(*object.Float).Value / float64(right.(*object.Integer).Value)
			}
		}
		if operator == "+" {
			return left.(*object.Float).Value + right.(*object.Float).Value
		} else if operator == "-" {
			return left.(*object.Float).Value - right.(*object.Float).Value
		} else if operator == "*" {
			return left.(*object.Float).Value * right.(*object.Float).Value
		} else if operator == "/" {
			return left.(*object.Float).Value / right.(*object.Float).Value
		}
	}

	if right.Type() == "FLOAT" {
		if left.Type() != "FLOAT" {
			if operator == "+" {
				return float64(left.(*object.Integer).Value) + right.(*object.Float).Value
			} else if operator == "-" {
				return float64(left.(*object.Integer).Value) - right.(*object.Float).Value
			} else if operator == "*" {
				return float64(left.(*object.Integer).Value) * right.(*object.Float).Value
			} else if operator == "/" {
				return float64(left.(*object.Integer).Value) / right.(*object.Float).Value
			}
		}
		if operator == "+" {
			return left.(*object.Float).Value + right.(*object.Float).Value
		} else if operator == "-" {
			return left.(*object.Float).Value - right.(*object.Float).Value
		} else if operator == "*" {
			return left.(*object.Float).Value * right.(*object.Float).Value
		} else if operator == "/" {
			return left.(*object.Float).Value / right.(*object.Float).Value
		}
	}

	return left.(*object.Integer).Value + right.(*object.Integer).Value
}

func evalStringInfixExpression(left, right object.Object) object.Object {

	leftVal := left.(*object.String).Value
	rightVal := right.(*object.String).Value
	//字符串拼接

	return &object.String{Value: leftVal + rightVal}

}

func evalExpressions(exps []ast.Expression, env *object.Environment) []object.Object {
	var result []object.Object

	for _, e := range exps {
		evaluated := Eval(e, env)
		/* if isError(evaluated) {
			return []object.Object{evaluated}
		} */
		result = append(result, evaluated)
	}

	return result
}

func evalIfExpression(ie *ast.IfExpression, env *object.Environment) object.Object {
	condition := Eval(ie.Condition, env)
	/* if isError(condition) {
		return condition
	} */
	if isTruthy(condition) {
		return Eval(ie.Consequence, env)
	} else if ie.Alternative != nil {
		return Eval(ie.Alternative, env)
	} else {
		return NULL
	}
}
func isTruthy(obj object.Object) bool {
	/* switch obj {
	case NULL:
		return false
	case TRUE:
		return true
	case FALSE:
		return false
	default:
		return true
	} */
	switch arg := obj.(type) {
	case *object.Integer:
		if arg.Value > 0 {
			return true
		}
		return false
	case *object.Float:
		if arg.Value > 0 {
			return true
		}
		return false
	case *object.String:
		return true
	case *object.Identifier:
		return isTruthy(obj)
	case *object.Boolean:
		if arg.Inspect() == "true" {
			return true
		}
		return false
	case *object.Null:
		return false
	case *object.Date:
		return true
	default:
		return false
	}
}

func evalForExpression(fe *ast.ForExpression, env *object.Environment) object.Object {

	val := Eval(fe.InitialValue.Value, env)
	num, err := strconv.Atoi(val.Inspect())
	if err != nil {
		// 处理错误
		fmt.Println("转换错误:", err)
	}
	//放到符号表中
	// env.Set(fe.InitialValue.Name.Value, &object.Integer{Value: int64(num)})
	env.Set(fe.InitialValue.Name.Value, object.Symbol{
		Name: fe.InitialValue.Name.Value,
		// Value: nil, // 延迟计算
		Value: &object.Integer{Value: int64(num)}, // 延迟计算
		Node:  nil,
	})
	for {

		//条件
		condition := Eval(fe.Condition, env)
		if condition.Inspect() == "true" {
			Eval(fe.Body, env)
			//增量 i++
			increment := Eval(fe.Increment, env)

			nums, err := strconv.Atoi(increment.Inspect())
			if err != nil {
				// 处理错误
				fmt.Println("转换错误:", err)
			}
			//放到符号表中
			// env.Set(fe.InitialValue.Name.Value, &object.Integer{Value: int64(nums + 1)})
			env.Set(fe.InitialValue.Name.Value, object.Symbol{
				Name: fe.InitialValue.Name.Value,
				// Value: nil, // 延迟计算
				Value: &object.Integer{Value: int64(nums + 1)}, // 延迟计算
				Node:  nil,
			})
		} else {
			break
		}

	}

	// return Eval(fe.Body, env)
	return NULL
}

func evalBlockStatement(block *ast.BlockStatement, env *object.Environment) object.Object {
	var result object.Object

	for _, statement := range block.Statements {
		result = Eval(statement, env)

		if result != nil {
			rt := result.Type()
			if rt == object.RETURN_VALUE_OBJ || rt == object.ERROR_OBJ {
				return result
			}
		}
	}

	return result
}

func applyFunction(funcName string, fn object.Object, args []object.Object) object.Object {
	/* fmt.Println(funcName)
	fmt.Printf("%#v\n", fn) */
	/* fmt.Printf("%T\n", fn)
	fmt.Println(funcName)
	fmt.Println(fn) */
	fmt.Printf("%#v\n", fn)

	//判断函数有没有被定义

	// fmt.Println(fn.Env)
	switch fn := fn.(type) {
	case *object.Function:
		extendedEnv := extendFunctionEnv(fn, args)
		//fn.Body就函数中的ast代码树，extendedEnv就是函数中的符号表
		evaluated := Eval(fn.Body, extendedEnv)

		return unwrapReturnValue(evaluated)

	case *object.Builtin:
		//判断内置函数中是否有这个函数
		/* if builtin, ok := fn.Fields[funcName]; ok {
			return builtin(args...)
		} else { */
		// fmt.Println("j yp li ma")
		return fn.Fn(args...)
		// }

	case *object.ModuleAccess:
		//判断内置函数中是否有这个函数
		return fn.Fn(args...)
	default:

		/*
			fmt.Printf("%#v\n", fn)
			fmt.Println(fn.Type())
			fmt.Println(fn.(*object.Error).Line) */
		// return exception.Evaluator(fn.(*object.Error).Line, "未定义的函数: %s", fn.Type())

		return exception.Evaluator(30000, fn.(*object.Error).Line, "未定义的函数: %s", funcName+"()")
	}
}

func extendFunctionEnv(fn *object.Function, args []object.Object) *object.Environment {
	env := object.NewEnclosedEnvironment(fn.Env, fn.Name)

	for paramIdx, param := range fn.Parameters {
		// env.Set(param.Value, args[paramIdx])
		env.Set(param.Value, object.Symbol{
			Name: param.Value,
			// Value: nil, // 延迟计算
			Value: args[paramIdx], // 延迟计算
			Node:  nil,
		})
	}

	return env
}

func unwrapReturnValue(obj object.Object) object.Object {
	if returnValue, ok := obj.(*object.ReturnValue); ok {
		return returnValue.Value
	}

	return obj
}

func evalIndexExpression(left, index object.Object, right object.Object) object.Object {
	switch {
	case left.Type() == object.ARRAY_OBJ && index.Type() == object.INTEGER_OBJ:
		return evalArrayIndexExpression(left, index, right)
	case left.Type() == object.HASH_OBJ:
		return evalHashIndexExpression(left, index, right)
	default:
		return exception.Evaluator(20001, 0, "不支持索引运算符: %s", left.Type())
	}
}

func evalArrayIndexExpression(array, index object.Object, right object.Object) object.Object {
	arrayObject := array.(*object.Array)
	idx := index.(*object.Integer).Value
	max := int64(len(arrayObject.Elements) - 1)

	if idx < 0 || idx > max {
		return NULL
	}
	if right != nil {
		arrayObject.Elements[idx] = right
	}
	return arrayObject.Elements[idx]
}

func evalHashLiteral(node *ast.HashLiteral, env *object.Environment) object.Object {
	pairs := make(map[object.HashKey]object.HashPair)

	for keyNode, valueNode := range node.Pairs {
		key := Eval(keyNode, env)
		if isError(key) {
			return key
		}
		hashKey, ok := key.(object.Hashable)
		if !ok {
			return exception.Evaluator(40000, 0, "不可用作哈希密钥: %s", key.Type())
		}

		value := Eval(valueNode, env)
		if isError(value) {
			return value
		}

		hashed := hashKey.HashKey()

		pairs[hashed] = object.HashPair{Key: key, Value: value}
	}
	return &object.Hash{Pairs: pairs}
}

func evalHashIndexExpression(hash, index object.Object, right object.Object) object.Object {
	hashObject := hash.(*object.Hash)

	key, ok := index.(object.Hashable)
	if !ok {
		return exception.Evaluator(40000, 0, "不可用作哈希密钥: %s", index.Type())
	}

	if right != nil {
		hashObject.Pairs[key.HashKey()] = object.HashPair{Key: index, Value: right}
	}
	pair, ok := hashObject.Pairs[key.HashKey()]
	if !ok {
		return NULL
	}

	return pair.Value
}

// parseImport 分析import语句
func parseImport(node *ast.ImportStatement, env *object.Environment) object.Object {

	if nativeModule, err := evaluator.module.LoadNativeModule(node.Path); err == nil {
		fmt.Println("nativeModule", nativeModule)

		// 创建模块对象
		modObj := &object.Module{
			Name: node.Path, IsLibrary: true,
		}
		env = object.NewEnclosedEnvironment(env, node.Path)

		// modObj.Exports = exports

		// 存储在环境中
		env.Set(node.Path, object.Symbol{
			Name: node.Path,
			// Value: nil, // 延迟计算
			Value: modObj, // 延迟计算
			Node:  nil,
		})

		return modObj
	}

	// 加载被导入的模块
	importedModule, err := evaluator.module.LoadModule(node.Path)
	if err != nil {
		fmt.Println("err")
		/* a.errors = append(a.errors, fmt.Errorf("Failed to load module %s: %v", stmt.Path, err))
		return */
	}
	fmt.Printf("%T\n", importedModule)
	fmt.Println("node.Path:", node.Path)
	fmt.Println("importedModule:", importedModule)

	switch importedModule := importedModule.(type) {
	case *request.RequestModule, *sqlite.SqliteModule:

		// currentModule:=&object.Module{Name: node.Path, IsLibrary: true}
		/* fmt.Println("importedModule:", importedModule.(*request.RequestModule))
		fmt.Println(importedModule.(*request.RequestModule).Methods()) */
		fmt.Printf("%v\n", importedModule.(*request.RequestModule))  // 基本格式
		fmt.Printf("%+v\n", importedModule.(*request.RequestModule)) // 显示结构体字段名
		fmt.Printf("%#v\n", importedModule.(*request.RequestModule)) // Go语法表示

		libMethods := importedModule.(*request.RequestModule).Methods()
		fmt.Println("libMethods:", libMethods)
		fmt.Printf("%#v\n", libMethods) // Go语法表示
		exports := make(map[string]object.Object)
		for key, method := range libMethods.Exports {
			fmt.Printf("%T\n", method)
			fmt.Println(key, method)
			fmt.Printf("%v\n", method)  // 基本格式
			fmt.Printf("%+v\n", method) // 显示结构体字段名
			fmt.Printf("%#v\n", method) // Go语法表示
			exports[key] = method.(*object.Builtin)
		}

		return &object.Module{Name: node.Path, IsLibrary: true, Exports: exports}
	default:
		module := importedModule.(*loader.Module)
		module.Scope = object.NewEnclosedEnvironment(env, node.Path)
		module.IsMain = false
		return Eval(module.AST, module.Scope)
	}

	/*
		// 词法分析
		lex := lexer.New(importedModule.Source)
		p := parser.New(lex)
		program := p.ParseProgram()

		newEvn := object.NewEnclosedEnvironment(env, node.Path)
		importedModule.AST = program
		importedModule.Scope = newEvn
		Eval(program, newEvn)
	*/

	/* env.Set("main", object.Symbol{
		Name: node.Name,
		// Value: nil, // 延迟计算
		Value: node.Path, // 延迟计算
		Node:  nil,
	}) */
	//放到符号表中
	// env.Set(node.Name.Value, val)
}

func moduleAccess(node *ast.ModuleAccess, env *object.Environment) object.Object {
	fmt.Println("moduleAccess:", node)
	// 确定模块在当前作用域中的名称（简称）
	// 规则：取导入路径的最后一段（如./demo/test/index的简称为"index"）
	moduleAlias := getModuleAlias(node.Module.Value)
	// 获取模块
	moduleObj, ok := evaluator.module.GetModule(moduleAlias)
	if !ok {
		fmt.Println("未知模块:%s", node.Module.Value)
	}

	switch moduleObj := moduleObj.(type) {
	case *loader.Module:
		// 获取模块符号表
		// module := moduleObj.(*object.Module)
		// return moduleObj.Scope.Get(node.Name.Value)
		// 解析符号
		if val, ok := moduleObj.Scope.Get(node.Name.Value); ok {
			/*
				// 如果是延迟计算的表达式，先计算
				if unevaluated, isUnevaluated := val.(*object.Unevaluated); isUnevaluated {
					val = e.Eval(unevaluated.Node)
					// module.Symbols.Set(ma.Name.Value, val) // 缓存计算结果
				}
			*/
			/* if !val.Exported {
				return exception.Evaluator(20001, 0, "null 值不能被访问")
			} */
			// fmt.Printf("%v ss:", val)
			return val.Value
			// return Eval(val.Node, moduleObj.Scope)
			// return val
		}
		// return newError("模块 %s 没有导出 %s", ma.Module.Value, ma.Name.Value)
	default:

		/* // 类型断言获取具体类型
		if reqMod, ok := moduleObj.(*request.RequestModule); ok {
			// 现在可以访问 RequestModule 的所有方法和字段
			// fmt.Println("Module name:", reqMod.Name())
			// for name, fn := range reqMod.Methods() {
			// 	fmt.Printf("Method %s: %v\n", name, fn)
			// }
			methods := reqMod.Methods()
			return &object.ModuleAccess{ModuleName: reqMod.Name(), Name: node.Name.Value, IsLibrary: true, Fn: methods[node.Name.Value]}
		}
		if sqlMod, ok := moduleObj.(*sqlite.SqliteModule); ok {
			methods := sqlMod.Methods()
			return &object.ModuleAccess{ModuleName: sqlMod.Name(), Name: node.Name.Value, IsLibrary: true, Fn: methods[node.Name.Value]}
		} */
	}

	return nil
}

// 获取模块在当前作用域中的别名（如./demo/test/index → "index"）
func getModuleAlias(importPath string) string {
	// 处理绝对路径：import "tc" → "tc"
	// 处理相对路径：import "./demo/test/index" → "index"
	return filepath.Base(importPath)
}

// evalDotExpression 处理点表达式
func evalDotExpression(left object.Object, right string) object.Object {
	switch obj := left.(type) {
	case *object.HttpResponse:
		if val, ok := obj.GetProperty(right); ok {
			return val
		}
		/* case *object.Module:
		if val, ok := obj.GetProperty(right); ok {
			return val
		} */
		// 其他类型处理...
	}

	return nil
}

/*
	 func evalPropertyAccess(node *ast.ObjectPropertyAccess, env *object.Environment) object.Object {
		obj := Eval(node.Object, env)
		if isError(obj) {
			return obj
		}

		switch obj := obj.(type) {
		case *object.Instance:
			val, ok := obj.GetProperty(node.Property.Value)
			if !ok {
				return newError("property not found: %s", node.Property.Value)
			}
			return val
		case *object.Module:
			// 模块也可以有属性
			val, ok := obj.Exports[node.Property.Value]
			if !ok {
				return newError("module has no property: %s", node.Property.Value)
			}
			return val
		default:
			return newError("cannot access property of %s", obj.Type())
		}
	}
*/
//统一属性/方法访问实现
func evalAccessExpression(node *ast.AccessExpression, env *object.Environment) object.Object {
	fmt.Println("node:", node)
	left := Eval(node.Left, env)
	if isError(left) {
		return left
	}
	// 获取属性/方法
	prop, ok := left.GetProperty(node.Property.Value)
	if !ok {
		// return newError("%s has no property %s", left.Type(), node.Property.Value)
		fmt.Sprintf("%s has no property %s", left.Type(), node.Property.Value)
	}

	// 如果是方法调用
	if node.Call {
		fmt.Printf("%v\n", left)  // 基本格式
		fmt.Printf("%+v\n", left) // 显示结构体字段名
		fmt.Printf("%#v\n", left) // Go语法表示

		fmt.Println("\nleft:", left)
		fmt.Println("\nprop start:")
		fmt.Println("prop:", prop)
		fmt.Println("prop end:\n")
		fmt.Println("evalAccessExpression:", node)
		fmt.Println("evalAccessExpression end:\n")

		fn, ok := prop.(*object.Builtin)
		if !ok {
			// return newError("%s is not callable", node.Property.Value)
			fmt.Sprintf("%s is not callable", node.Property.Value)
		}
		//获取函数中的参数
		args := evalExpressions(node.Args, env)
		if len(args) == 1 && isError(args[0]) {
			return args[0]
		}

		return applyFunction(node.Property.Value, fn, args)
	}

	// 普通属性访问
	return prop
}
